package org.example;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class 第二十七章_反射 {
    public static void main(String[] args) throws Exception {
        //回去class对象
        //通过类字面量
        Class<String> stringClass = String.class;
        //通过对象实例
        String i = "2222";
        Class<? extends String> aClass = i.getClass();
        //通过Class.forName() 方法
        Class<?> clazz = Class.forName("java.lang.String");

        clazz = P1.class;
        //反射创建对象
        Object newInstance = clazz.getConstructor(String.class).newInstance("小明");

        Field name = clazz.getDeclaredField("name");//获取字段
        name.setAccessible(true);//设置共有
        Object name1 = name.get(newInstance);//获取值

        //修改值
        name.set(newInstance,"aaaa");
        name1 = name.get(newInstance);

        //调用方法
        Method greetMethod = clazz.getMethod("greet",String.class);
        System.out.println(greetMethod.invoke(newInstance,"null"));

        System.out.println(name1.toString());
    }

    static class P1{
        private String name;

        public P1(String name){
            this.name = name;
        }

        public void greet(String message) {
            System.out.println(name + " says: " + message);
        }
    }
}
